///////////////////////////////////
//         ajax im v3.1          //
//    AJAX Instant Messenger     //
//   Copyright (c) 2006-2007     //
// unwieldy studios/Joshua Gross //
//  http://unwieldy.net/ajaxim/  //
//   Do not remove this notice   //
///////////////////////////////////

// Configurable Options //

// Notification // 
//网站即时通讯的名称
var web_name = "晓春在线平台";
//用户的角色
var contextPathJs = "";
var user_role = '-1';
var useBlinker    = true;           // Show new message in titlebar when window isn't active.
var blinkSpeed    = 1000;           // How fast to change between the titles when "blinking" (in milliseconds).
var pulsateTitles = true;           // Pulsate (blink) IM window titles on new IM when they are not the active window.
var audioNotify   = true;           // By default, play sounds upon getting an IM?

// Server //
var pingFrequency = 2500;           // How often to ping the server (in milliseconds). Best range between 2500 and 3500 ms.
var pingTo        = contextPathJs+'/imService.do';  // The file that is the "server".

// Windows //
var imWidth       = 310;            // Default IM window width
var imHeight      = 435;            // Default IM window height
var imHistory     = true;           // "Save" conversations with buddies throughout the session
var imDetachable  = true;           // Enable/Disable ability to detach windows from the application
var advPaneHeight = 100;
// Smilies //
var smilies = [                    // Smiley format: 'smiley~imagename.ext',
   ":)~smile.gif",
   ":-)~smile.gif",
   ":D~grin.gif",
   ":-D~grin.gif",
   ";)~wink.gif",
   ";-)~wink.gif",
   ":[~embarassed.gif",
   ":-[~embarassed.gif",
   ":*~love.gif",
   ":-*~love.gif",
   ":(~sad.gif",
   ":-(~sad.gif",
   ":'(~cry.gif",
   ":'-(~cry.gif",
   "8-)~cool.gif",
   "&gt;:o~angry.gif",
   "&gt;:-o~angry.gif",
   ":O~surprised.gif",
   ":-O~surprised.gif",
   ":|~serious.gif",
   ":-|~serious.gif",
   ":-S~sick.gif",
   ":P~tongue.gif",
   ":-P~tongue.gif",
   "&lt;3~heart.gif",
   "&lt;33~heart.gif",
   "&lt;\/3~heartbroken.gif",
   "&lt;\\3~heartbroken.gif"
];

// Other //
var alertCSS      = 'alphacube';    // CSS file for alerts and login/add buddy/IM anyone windows
var alertWidth    = 400;            // Alert window width (see above)
var windowCSS     = 'default';      // CSS file for all other windows (buddylist, IMs)
var buddyListLoc  = 1;              // Buddylist location: 0=left, 1=right

// End Configurable Options //

// Begin Code                                   //
// Note: Do not edit below this line unless you //
//       know what you are doing!               //
var user='';
var pass='';
var isAway=0;
var awayMessage = '';
var curSelected='';
var loggedIn=false;
var IMWindows={};
var titlebarBlinker=false;
var defaultTitle=document.title;
var blinkerTimer;
var pingTimer;
var buddyList = {};
var toWin;
var newWin, newWinRcvd;

window.onbeforeunload = function(event) {
   if(isIE || !event) event = window.event;
   if(event && user.length > 0 && user_role != '0') {
      var text = "确定后将要退出"+web_name+"的即时通讯.";
      if(isIE) event.returnValue = text;
      window.onbeforeunload = function() { };
      return text;
   }
}

window.onunload = function() {
   if(user.length > 0) {
      logout();
   }
}

var buddyListWin;

function fixBuddyList() {
   if(buddyListWin && buddyListWin.isVisible()) {
      buddyListWin.setSize(210, (browserHeight() - 50));
      buddyListWin.setLocation((((browserHeight()-40) / 2) - (buddyListWin.getSize()['height'] / 2)), (buddyListLoc == 0 ? 10 : (browserWidth() - buddyListWin.getSize()['width'] - 10)));
      sizeBuddyList();
   }
}

function login() {
   var username = $('username').value;
   var password = $('password').value;
   user_role = $('userRole').value;
   var signonButton = $('signon_button');
   signonButton.onclick = function() { };
   if(username == 'undefined' || username.length < 1){
   		alert("用户名不能为空！");
   }
   if(password == 'undefined' || password.length < 1){
   		alert("密码不能为空！");
   }
   if(user_role == 'undefined' || user_role == '-1'){
   		alert("请选择您的身份！");
   } 
   var xhConn = new XHConn();
   xhConn.connect(pingTo, "POST", "call=login&from="+username+"&pwd="+hex_md5(password)+"&password="+password+"&role="+user_role,
      function(xh) {
         if(xh.responseText == 'invalid') {
            $('login_error_msg').innerHTML = '用户名或密码错误！';
            $('login_error_msg').style.display = 'block'; 
            new Effect.Shake('modal');
            signonButton.onclick = function() { login();return false; };
         } else if (xh.responseText.indexOf('imenterpriseSuc') != -1){
			var enId = xh.responseText.split("_");
			window.location.href=contextPathJs+'/imEnterpriseService.do?action=getImEn&enterpriseId='+enId[1];
		 } else {
            user = username;
            pass = hex_md5(password);
            defaultTitle = document.title = document.title + ': ' + user;
            window.onresize = fixBuddyList;
            if(!$('bl')) {
               buddyListWin = new Window('bl', {className: "dialog", width: 210, height: (browserHeight() - 60), zIndex: 100, resizable: true, 
                                                title: web_name+"即时通", draggable: true, closable: false, maximizable: false, detachable: false, minWidth: 205, minHeight: 150,
                                                showEffectOptions: {duration: 0}, hideEffectOptions: {duration: 0}});
            }
			//meconsea 去掉增加、删除好友的功能
            buddyListWin.getContent().innerHTML = '<div id="blTopToolbar"><span  class="toolbarButton">互动平台</span><div id="statusSettings"><input type="text" id="customStatus" onkeypress="processCustomAway(event);" style="display:none" onblur="if($(\'customStatus\').style.display != \'none\') { $(\'customStatus\').style.display = \'none\'; $(\'curStatus\').style.display = \'block\'; }" /><a href="#" id="curStatus" onclick="toggleStatusList();return false;">在线</a></div></div><div id="blContainer"><ul id="buddylist" class="sortable box"><li style="display:none"></li></ul></div><div id="blBottomToolbar"><a href="#" style="-moz-outline-style: none;" onclick="logout();return false;"><img src="'+contextPathJs+'/im/images/'+windowCSS+'/signoff.png" style="border:0;" alt="登出"/></a></div>';
			//buddyListWin.getContent().innerHTML = '<div id="blTopToolbar"><span class="toolbarButton"><img id="addbuddy" src="'+contextPathJs+'/im/images/'+windowCSS+'/addbuddy.png" class="toolbarButton" onclick="new_buddy_dialog();" alt="添加好友" title="添加好友" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" onmousedown="buttonDown(this);" onmouseup="buttonNormal(this);" /></span><span class="toolbarButton"><img id="removebuddy" src="'+contextPathJs+'/im/images/'+windowCSS+'/removebuddy.png" class="toolbarButton" onclick="remove_buddy_dialog();" alt="删除好友" title="删除好友" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" onmousedown="buttonDown(this);" onmouseup="buttonNormal(this);" /></span><span class="toolbarButton"><img id="toggleaudio" src="'+contextPathJs+'/im/images/'+windowCSS+'/audio_'+(audioNotify ? 'on' : 'off')+'.png" onclick="toggleAudio();" alt="提示音" title="Toggle Audio" /></span><div id="statusSettings"><input type="text" id="customStatus" onkeypress="processCustomAway(event);" style="display:none" onblur="if($(\'customStatus\').style.display != \'none\') { $(\'customStatus\').style.display = \'none\'; $(\'curStatus\').style.display = \'block\'; }" /><a href="#" id="curStatus" onclick="toggleStatusList();return false;">在线</a></div></div><div id="blContainer"><ul id="buddylist" class="sortable box"><li style="display:none"></li></ul></div><div id="blBottomToolbar"><a href="#" style="-moz-outline-style: none;" onclick="logout();return false;"><img src="'+contextPathJs+'/im/images/'+windowCSS+'/signoff.png" style="border:0;" alt="登出" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" onmousedown="buttonDown(this);" onmouseup="buttonNormal(this);" /></a></div>';
			buddyListWin.getContent().oncontextmenu = function() { return false; };
            $('bl_minimize').style.left = (buddyListWin.getSize()['width'] - 21) + 'px';
            sizeBuddyList();
            buddyListWin.showCenter(false, (((browserHeight()-40) / 2) - (buddyListWin.getSize()['height'] / 2)), (buddyListLoc == 0 ? 10 : (browserWidth() - buddyListWin.getSize()['width'] - 10)));
            buddyListWin.toFront();

            if(trim(xh.responseText).length == 0) logout();
			//meconsea 

            var response = xh.responseText.parseJSON();
            //meconsea
			//alert(response.buddy);
            pingTimer = setInterval(ping, pingFrequency);
            $('modal').style.display = 'none';   
			//meconsea 解析Json
			var enBuddyList = response.buddy;         
			for(var eLn in enBuddyList){
				if(eLn != 'toJSONString'){
					var eEle = enBuddyList[eLn];
					var eEleEnterpriseId = eEle.enterpriseId;
					var eEleEnterpriseName = eEle.enterpriseName;
					var eEleEnterpriseRealName = eEle.enterpriseRealName;
					var eEleEnterpriseCreditLevel = eEle.enterpriseCreditLevel;
					var eExperts = eEle.experts;
					for( var expertIndex in eExperts){
						if(expertIndex != 'toJSONString'){
							var eEUser= eExperts[expertIndex];
							var eEUserName = eEUser.username;
							var eEUserNickName = eEUser.nickname;
							var eEUserCreditLevel = eEUser.creditlevel;
							var eEUserOnline = eEUser.isOnline;
							if(!$(eEUserName+'_blItem'))addBuddyToListAll(eEUserName,eEUserNickName,eEUserCreditLevel, eEleEnterpriseName,eEleEnterpriseRealName,eEleEnterpriseCreditLevel);
							$(eEUserName+'_blItem').style.display='block';
							//加入组
							moveBuddy(eEUserName, eEleEnterpriseName);
							if(eEUserOnline == 0 || eEUserOnline == 50){//离线
								$(eEUserName+'_blImg').src = contextPathJs+'/im/images/offline.png';
							}else if(eEUserOnline == 2){//离开
								 $(eEUserName+'_blImg').src = contextPathJs+'/im/images/away.png';  
							}else{
								$(eEUserName+'_blImg').src = contextPathJs+'/im/images/online.png'; 
							}
						}
					}
				}
			}
         }
      }); 
}

function logout() {
   if(user == '' || pass == '') return;
   /**
   var xmlhttp=false;
   if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
     xmlhttp = new XMLHttpRequest();
   }
   
   xmlhttp.open('POST', pingTo, false);
   xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
   xmlhttp.send('call=logout&from='+user+'&pwd='+pass);
   
   clearTimeout(pingTimer);
**/
   defaultTitle = document.title = '(*^__^*)欢迎再次光临F2F(*^__^*) ';
   user = '';
   pass = '';
   isAway = 0;
   awayMessage = '';
   window.onresize = function() { };
   buddyListWin.hide();
   for(var name in IMWindows) {
      if(typeof($(name + '_im')) != 'undefined') {
         try {
            if(IMWindows[name].popup)
               IMWindows[name].popup.close();
            else
               IMWindows[name].destroy();
         } catch(e) { }
      }
   }
   Dialog.alert('<span class="dialog_long_label">你已成功退出!</span>',
                { windowParameters: {className:alertCSS, width:alertWidth, height: 85}, 
                  okLabel: "重新连接",
                  ok:function(win) {
                     try {
                        window.location.reload();
                     } catch(e) { }
                  }
                });
}

 
function register() {
   user_role='0'; 
   window.location=contextPathJs+'/im/enReg.jsp';
}
 
function ping() { 
   var xhConn = new XHConn();
   
   xhConn.connect(pingTo, "POST", "call=ping&from="+user+"&pwd="+pass+"&away="+isAway+'&role='+user_role,
      function(xh) {
         var i;

         if(xh.responseText == 'not_logged_in') {
            logout();
            return;
         }     
         
         if(trim(xh.responseText).length == 0) return;
		 //alert("isAway == "+isAway+"--->"+xh.responseText);
         var response = xh.responseText.parseJSON();
         
         var from, data;
         for(i=0; i<response.numMessages; i++) {
            from = response.messages[i].sender;
            data = response.messages[i].message;
            who  = (response.messages[i].recipient == user ? from : response.messages[i].recipient);
         
            if(!$(who + '_im')) {
               createIMWindow(who, who);
            } else {
               if(!IMWindows[who].detached && !IMWindows[who].isVisible()) {
                  IMWindows[who].show();
                  setTimeout("scrollToBottom('" + who + "_rcvd')", 125);
               }
            }
            
            Stamp = new Date(); var h = String(Stamp.getHours()); var m = String(Stamp.getMinutes()); var s = String(Stamp.getSeconds());
            h = (h.length > 1) ? h : "0"+h; m = (m.length > 1) ? m : "0"+m;
            var curIM = (!IMWindows[who].detached ? $(who+"_rcvd") : IMWindows[who].popup.$(who+"_rcvd")); 
            data = data.replace(/(\s|\n|>|^)(\w+:\/\/[^<\s\n]+)/, '$1<a href="$2" target="_blank">$2</a>');
            data = emoteReplace(data, smilies);
            if(data.replace(/<([^>]+)>/ig, '').indexOf('/me') == 0)
               curIM.innerHTML = curIM.innerHTML + "<b class=\"userB\">[" + h + ":" + m + "] <i>" + from + ' ' + data.replace(/<([^>]+)>/ig, '').replace(/\/me/, '') + "</i></b><br>\n";
            else
               curIM.innerHTML = curIM.innerHTML + "<b class=\"userB\">[" + h + ":" + m + "] " + from + ":</b> " + data + "<br>\n";
            curIM.scrollTop = curIM.scrollHeight - curIM.clientHeight + 6;
            
            if(curIM.innerHTML.toLowerCase().replace(/<\S[^>]*>/g, '').indexOf(user.toLowerCase()+': (auto-reply)') == -1 && isAway == 1 && who == from) {
               $(from+"_sendBox").value = '(Auto-Reply) ' + awayMessage;
               sendMessage(from);
            }
            
            if(Windows.getFocusedWindow().getId() != who + "_im" && pulsateTitles == true) {
               new Effect.Pulsate(who + '_im_top');
            }

            if(titlebarBlinker == true && useBlinker == true) {
               clearTimeout(blinkerTimer);
               setTimeout("titlebarBlink('"+who+"', \""+data.replace(/\"/, '\"').replace(/<([^>]+)>/ig, '')+"\", 0)", blinkSpeed);
            }
            curIM = null;
         }
         if(response.numMessages > 0 && audioNotify == true) soundManager.play('msg_in', 1, true);
                
         from = null; data = null;
         var group = '';
         var buddy = '';
         var event = '';
         for(i=0; i<response.numEvents; i++) {
            from = response.events[i].sender;
            data = response.events[i].event;
            who  = (response.events[i].recipient == user ? from : response.events[i].recipient);
            
            event = data.split(',');
            switch(event[0]) {
               case 'status':
                  group = response.events[i].group;
				  var egRealName = response.events[i].groupName;
				  var egCreditlevel = response.events[i].groupCreditLevel;
                  if(!$(group.replace(/\s/, '_')+'_group') && group != 'toJSONString'){
					addGroupToListAll(group,egRealName,egCreditlevel);
					//addGroupToList(group);
				  }
                  if(!$(from+'_blItem')) {
					 var ugNickName = response.events[i].nickName;
					 var ugCreditLevel = response.events[i].creditLevel;
					 addBuddyToListAll(from,ugNickName,ugCreditLevel,group,egRealName,egCreditlevel);
                     //addBuddyToList(from, group);
                     //buddyList[group][buddyList[group].length] = from;
                     $(from+'_blItem').style.display='block';
                  }
                  
                  if(event[1] == 0 || event[1] == 50) {
                     //moveBuddy(from, 'Offline');
                     $(from+'_blImg').src = contextPathJs+'/im/images/offline.png';
                  } else if(event[1] == 2) {
                     //moveBuddy(from, group);
                     $(from+'_blImg').src = contextPathJs+'/im/images/away.png';            
                  } else {
                     //moveBuddy(from, group);
                     $(from+'_blImg').src = contextPathJs+'/im/images/online.png';
                  }
                  break;
               case 'chat':
                  var rcvdBox = $(event[2]+"_rcvd");
                  Stamp = new Date(); var h = String(Stamp.getHours()); var m = String(Stamp.getMinutes()); var s = String(Stamp.getSeconds());
                  h = (h.length > 1) ? h : "0"+h; m = (m.length > 1) ? m : "0"+m;
                  if(event[1] == 'join') {
                     if(!$(from+'_blItem')) addBuddyToList(from, event[2]);
                     rcvdBox.innerHTML = rcvdBox.innerHTML + "<b class=\"userB\">[" + h + ":" + m + "] <i>"+from+" has joined.</i></b><br>";
                     scrollToBottom(event[2]+"_rcvd");
                  } else if(event[1] == 'left') {
                     if(typeof(response.events[i]['group']) == 'object') deleteBuddyFromList(from);
                     rcvdBox.innerHTML = rcvdBox.innerHTML + "<b class=\"userB\">[" + h + ":" + m + "] <i>"+from+" has left.</i></b><br>";
                     scrollToBottom(event[2]+"_rcvd");
                  }
                  break;
            }
            event = null;
         }
         from = null; data = null; who = null;
         
      }
   );
   xhConn = null;
}

function sendMessage(winName) {
   var xhConn = new XHConn();
   
   var isBold      = ($(winName + '_sendBox').style.fontWeight == '400' ? 'false' : 'true');
   var isItalic    = ($(winName + '_sendBox').style.fontStyle == 'normal' ? 'false' : 'true');
   var isUnderline = ($(winName + '_sendBox').style.textDecoration == 'none' ? 'false' : 'true');
   var fontName    = $(winName + '_setFont').innerHTML;
   var fontSize    = $(winName + '_setFontSize').innerHTML;
   var fontColor   = $(winName + '_setFontColorColor').style.backgroundColor;

   if(trim($(winName+"_sendBox").value).length > 0) {
      var sBox = $(winName + '_sendBox').value;
      $(winName+"_sendBox").value = '';
      xhConn.connect(pingTo, "POST", "call=send&from="+user+"&pwd="+pass+"&recipient="+winName+"&role="+user_role+"&bold="+isBold+"&italic="+isItalic+"&underline="+isUnderline+"&font="+fontName+"&fontsize="+fontSize+"&fontcolor="+fontColor+"&msg="+encodeURIComponent(sBox.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/&/g, "<amp>")),
         function(xh) {
            if(xh.responseText == 'sent') {
               // do nothing!
            } else if(xh.responseText == 'not_online') {
			   if(winName.indexOf("guest_") == -1){
	               var rcvdBox = $(winName+"_rcvd");
	               rcvdBox.innerHTML = rcvdBox.innerHTML + '<span style="color:#FF0000"><b>对方离线，上线后将收到您的消息。</b></span><br>';
	               scrollToBottom(winName+"_rcvd");
			   }
            } else if(xh.responseText == 'too_long') {
               var rcvdBox = $(winName+"_rcvd");
               rcvdBox.innerHTML = rcvdBox.innerHTML + '<span style="color:#FF0000"><b>消息太长。</b></span><br>';
               scrollToBottom(winName+"_rcvd");
            } else if(xh.responseText == 'not_logged_in') {
               logout();
            } else {
               alert('发送消息时发生了错误！');
            }
            $(winName+"_sendBox").focus();
         }
      );

      var sentText = sBox;
      sentText = sentText.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/<([^>]+)>/ig, '').replace(/(\s|\n|>|^)(\w+:\/\/[^<\s\n]+)/, '$1<a href="$2" target="_blank">$2</a>');
      sentText = emoteReplace(sentText, smilies);
      var rcvdBox = $(winName+"_rcvd");
      Stamp = new Date(); var h = String(Stamp.getHours()); var m = String(Stamp.getMinutes()); var s = String(Stamp.getSeconds());
      h = (h.length > 1) ? h : "0"+h; m = (m.length > 1) ? m : "0"+m;
      if(sentText.replace(/<([^>]+)>/ig, '').indexOf('/me') == 0)
         rcvdBox.innerHTML = rcvdBox.innerHTML + "<b class=\"userA\">[" + h + ":" + m + "] <i>" + user + ' ' + sentText.replace(/<([^>]+)>/ig, '').replace(/\/me/, '') + "</i></b><br>\n";
      else
         rcvdBox.innerHTML = rcvdBox.innerHTML + "<b class=\"userA\">[" + h + ":" + m + "] " + user + ":</b> <span style=\"font-family:" + fontName + ",sans-serif;font-size:" + fontSize + "px;color:" + fontColor + ";\">" + (isBold == 'true' ? "<b>" : "") + (isItalic == 'true' ? "<i>" : "") + (isUnderline == 'true' ? "<u>" : "") + sentText + (isBold == 'true' ? "</b>" : "") + (isItalic == 'true' ? "</i>" : "") + (isUnderline == 'true' ? "</u>" : "") + "</span><br>\n";
      scrollToBottom(winName+"_rcvd");
      if(audioNotify == true) soundManager.play('msg_out', 1, true);
   }
}

function emoteReplace(str, itemsList) {
   var r;
   for(var i=0; i<itemsList.length; i++) {
      r = itemsList[i].split('~');
      if(str.indexOf(r[0]) > -1)
         str = str.replace(new RegExp(regExpEscape(r[0]), 'g'), '<img src="'+contextPathJs+'/im/images/emoticons/' + r[1] + '" alt="' + r[1] + '" title="' + r[0] + '" />');
   }
   return str;
}

function regExpEscape(text) {
  if (!arguments.callee.sRE) {
    var specials = [
      '/', '.', '*', '+', '?', '|',
      '(', ')', '[', ']', '{', '}', '\\'
    ];
    arguments.callee.sRE = new RegExp(
      '(\\' + specials.join('|\\') + ')', 'g'
    );
  }
  return text.replace(arguments.callee.sRE, '\\$1');
}

function newIMWindow() { 
   if($('sendto').value.replace(/^\s*|\s*$/g,"").length > 0) {
      var toWhom = $('sendto').value;

      if(!$(toWhom + '_im')) {
         createIMWindow(toWhom, toWhom);
      } else {
         if(!IMWindows[toWhom].isVisible()) {
            IMWindows[toWhom].show();
            setTimeout("scrollToBottom('" + toWhom + "_rcvd')", 125);
         }
      }
      
      Windows.close('newIM');
      IMWindows[toWhom].toFront();
      setTimeout("$('"+toWhom+"_sendBox').focus()", 125);
   } else {
      $('newim_error_msg').innerHTML = 'Please enter a proper username!';
   } 
}

function createIMWindow(name, imTitle) {
   var imLeft = Math.round(Math.random()*(browserWidth()-360))+'px';
   var imTop  = Math.round(Math.random()*(browserHeight()-400))+'px';

   IMWindows[name] = new Window(name + '_im', {className: "dialog", width: 320, height: 435, top: imTop, left: imLeft,
                                               resizable: true, title: imTitle, draggable: true, detachable: imDetachable, minWidth: 320, minHeight: 250,
                                               showEffectOptions: {duration: 0}, hideEffectOptions: {duration: 0}});
   IMWindows[name].getContent().innerHTML = '<div class="rcvdMessages" id="' + name + '_rcvd"></div>' + "\n" +
                                            '<div class="imToolbar" id="' + name + '_toolbar" onmousemove="return false;" onselectstart="return false;">'+
											'<img src="'+contextPathJs+'/im/images/'+windowCSS+'/bold_off.png" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" onclick="toggleBold(\'' + name + '\');" onmousedown="return false;" alt="Bold" id="' + name + '_bold" /> ' +
                                            '<img src="'+contextPathJs+'/im/images/'+windowCSS+'/italic_off.png" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" onclick="toggleItalic(\'' + name + '\');" onmousedown="return false;" alt="Italic" id="' + name + '_italic" /> '+
                                            '<img src="'+contextPathJs+'/im/images/'+windowCSS+'/underline_off.png" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" onclick="toggleUnderline(\'' + name + '\');" onmousedown="return false;" alt="Underline" id="' + name + '_underline" /></div>' +
                                            ' <a href="#" class="setFontLink" id="' + name + '_setFont" onclick="toggleFontList(\'' + name + '\');return false;" onselectstart="return false;">Tahoma</a>' +
                                            ' <a href="#" class="setFontSizeLink" id="' + name + '_setFontSize" onclick="toggleFontSizeList(\'' + name + '\');return false;" onselectstart="return false;">12</a>' +
                                            ' <a href="#" class="setFontColorLink" id="' + name + '_setFontColor" onclick="toggleFontColorList(\'' + name + '\');return false;" onselectstart="return false;">'+
											'<div id="' + name + '_setFontColorColor" style="width:14px;height:14px;display:block;"></div></a>' +
                                            ' <a href="#" class="insertEmoticonLink" id="' + name + '_insertEmoticon" onclick="toggleEmoticonList(\'' + name + '\');return false;" onselectstart="return false;">'+
											'<img src="'+contextPathJs+'/im/images/emoticons/mini_smile.gif" width="14" height="14" style="border:0;" /></a>' +
                                            "\n" + '<div style="overflow:auto;">'+
											'<textarea class="inputText" id="'+name+'_sendBox" onfocus="blinkerOn(false);" onkeypress="return keyHandler(event,'+"'"+name+"'"+');"></textarea></div>'+
											"\n" + '<div class="advMessages" id="'+name+'_advPane"></div>';//'\n'+'<div class="advMessages" id="'+ name +'_advPane">sdfsdfsdfsdfsdf</div>';
   $(name + '_rcvd').style.height = (IMWindows[name].getSize().height - advPaneHeight - 103) + 'px';
   $(name + '_rcvd').style.width = (IMWindows[name].getSize().width - 10) + 'px';

   $(name + '_toolbar').style.top = (IMWindows[name].getSize().height - advPaneHeight - 73) + 'px';
   $(name + '_toolbar').style.width = (IMWindows[name].getSize().width - 10) + 'px';
   
   $(name + '_setFont').style.top = (IMWindows[name].getSize().height - advPaneHeight - 65) + 'px';
   
   $(name + '_setFontSize').style.top = (IMWindows[name].getSize().height - advPaneHeight - 65) + 'px';
   
   $(name + '_setFontColor').style.top = (IMWindows[name].getSize().height - advPaneHeight - 65) + 'px';
   $(name + '_setFontColorColor').style.backgroundColor = '#000';
   
   $(name + '_insertEmoticon').style.top = (IMWindows[name].getSize().height - advPaneHeight - 65) + 'px';

   $(name + '_sendBox').style.top = (IMWindows[name].getSize().height - advPaneHeight - 45) + 'px';
   $(name + '_sendBox').style.left = '2px';
   $(name + '_sendBox').style.width = (IMWindows[name].getSize().width  - 16) + 'px';
   $(name + '_sendBox').style.fontWeight = '400';
   $(name + '_sendBox').style.fontStyle = 'normal';
   $(name + '_sendBox').style.textDecoration = 'none';
   //debug
   //mecosnea 
   $(name + '_advPane').style.top = (IMWindows[name].getSize().height - advPaneHeight+20)+'px';
   $(name + '_advPane').style.left = '5px';
   $(name + '_advPane').style.width = (IMWindows[name].getSize().width - 10) + 'px';
   IMWindows[name].show();
   IMWindows[name].toFront();
   setTimeout("$('"+name+"_sendBox').focus();", 250);
   //初始化广告
   initAdvPane(name);
}
//恢复到IE效果
function detachIMWindow(name) {
   newWin = name;
   newWinRcvd = $(name + '_rcvd').innerHTML;
   IMWindows[name].hide();
   var temp = IMWindows[name];
   var popupWin = window.open('./popup.html', name + '_im', 'left='+IMWindows[name].getLocation()['left']+',top='+IMWindows[name].getLocation()['top']+',width=320,height=435,toolbar=0,location=1,status=0,menubar=0,resizable=1,scrollbars=0');
   IMWindows[name] = {};
   IMWindows[name].popup = popupWin;
   IMWindows[name].isVisible = function() { return true; };
   IMWindows[name].show = function() { return true; };
   IMWindows[name].detached = true;
   IMWindows[name].old = temp;
}

function joinRoom(room) {
 var xhConn = new XHConn();
   xhConn.connect(pingTo, "POST", "call=joinroom&from="+user+"&pwd="+pass+"&room="+room,
      function(xh) {
         if(xh.responseText.indexOf('"') == -1) {
            switch(xh.responseText) {
               case 'already_joined':
                  $('newroom_error_msg').innerHTML = 'You are already in "' + room + '".';
                  break;
               case 'room_is_user':
                  $('newroom_error_msg').innerHTML = 'The chosen room name is invalid.';
                  break;
               case 'invalid_chars':
                  $('newroom_error_msg').innerHTML = 'Room name contains invalid characters!';
                  break;
            }
         } else {
            if(!$(room + '_im')) {
               createIMWindow(room.toLowerCase(), room.toLowerCase());
            } else {
               if(!IMWindows[room].isVisible()) {
                  IMWindows[room].show();
                  setTimeout("scrollToBottom('" + room + "_rcvd')", 125);
               }
            }
            var users = xh.responseText.parseJSON().users;
            if(!$(room.replace(/\s/, '_')+'_group')) addGroupToList(room);
            for(var i=0; i<users.length; i++) {
               if(!$(users[i]+'_blItem')) addBuddyToList(users[i], room);
            }
            Windows.close('newRoom');
            IMWindows[room].toFront();
            setTimeout("$('"+room+"_sendBox').focus()", 125);
         }
		  });
}

function leaveRoom(room){
   var xhConn = new XHConn();
   xhConn.connect(pingTo, "POST", "call=leaveroom&from="+user+"&pwd="+pass+"&room="+room,
      function(xh) {
         if(xh.responseText=='left')
            deleteGroupFromList(room);
      });
}

function keyHandler(e, name) {
   var asc = document.all ? event.keyCode : e.which;
   
   if(asc == 13) {
      sendMessage(name);
      return false;
   }
   
   return true;
}

function loginHandler(e) {
   var asc = document.all ? event.keyCode : e.which;
   if(asc == 13) login();
   return asc != 13;
}

function destroyIMWindow(name) {
   var toKill = $(name);
   toKill.parentNode.removeChild(toKill);
}

function addBuddyToList(username, groupname) {
   if(!$(groupname.replace(/\s/, '_') + '_group')) addGroupToList(groupname);

   var groupList = $(groupname.replace(/\s/, '_') + '_group');

   groupList.innerHTML += '<li id="'+username+'_blItem" class="buddy" onmousedown="clickBuddy(\''+username+'\');return false;" onselectstart="return false;" onmouseover="selectBuddy(this, \''+username+'\', true);" onmouseout="selectBuddy(this, \''+username+'\', false);" ondblclick="onBuddyDblClick(\''+username+'\');">&nbsp;&nbsp;&nbsp;&nbsp;<img src="'+contextPathJs+'/im/images/online.png" width="16" height="16" alt="" id="'+username+'_blImg">&nbsp;'+username+'</li>';
   $(username + '_blItem').style.listStyleType = 'none';
}

//meconsea 增加用户昵称和信用等级
function addBuddyToListAll(username,userNickName,userCreditLevel, groupname, groupRealName,groupCreditLevel){
	if(!$(groupname.replace(/\s/, '_') + '_group')) addGroupToListAll(groupname, groupRealName,groupCreditLevel);
	var groupList = $(groupname.replace(/\s/, '_') + '_group');
	var xx = '';
   for(var i = 1; i <= userCreditLevel; i++){
	    xx += '<img src="'+contextPathJs+'/im/images/xx.ico" width=12px height=12px>';
   }
   userNickName = userNickName.replace(/[\u0000-\u00ff]/g,'');
	groupList.innerHTML += '<li id="'+username+'_blItem" class="buddy" onmousedown="clickBuddy(\''+username+'\');return false;" onselectstart="return false;" onmouseover="selectBuddy(this, \''+username+'\', true);" onmouseout="selectBuddy(this, \''+username+'\', false);" ondblclick="onBuddyDblClick(\''+userNickName+'\');">&nbsp;&nbsp;&nbsp;&nbsp;<img src="'+contextPathJs+'/im/images/online.png" width="16" height="16" alt="" id="'+username+'_blImg">&nbsp;'+userNickName+' '+xx+'</li>';
    $(username + '_blItem').style.listStyleType = 'none';
}
//meconsea 增加企业实际名称和信用等级
function addGroupToListAll(groupname, groupRealName,groupCreditLevel){
	var bList = $('buddylist');
   var zz = '';
   for(var i = 1; i <= groupCreditLevel; i++){
	    zz += '<img src="'+contextPathJs+'/im/images/zz.gif" width=12px height=12px>';
   }
   groupRealName = groupRealName.replace(/[\u0000-\u00ff]/g,'');
   bList.innerHTML = (groupname=='Offline' ? bList.innerHTML : '') + '<li id="' + groupname.replace(/\s/, '_') + '_groupTop" class="groupTop" onmousedown="return false;" onselectstart="return false;" onclick=" toggleGroup(\'' + groupname + '\');"><img id="' + groupname.replace(/\s/, '_') + '_groupArrow" src="'+contextPathJs+'/im/images/' + windowCSS + '/arrow.png" />&nbsp;&nbsp;' + groupRealName + 
                     '  '+zz + '</li>' + "\n" + '<ul id="' + groupname.replace(/\s/, '_') + '_group" class="group"></ul>' + (groupname!='Offline' ? bList.innerHTML : '');
}

function moveBuddy(username, groupname) {
   if(groupname == null) return;
   if($(username+'_blItem').parentNode.id == $(groupname.replace(/\s/, '_') + '_group')) return;
   if(!$(groupname.replace(/\s/, '_') + '_group')) addGroupToList(groupname);
   
   $(groupname.replace(/\s/, '_') + '_group').insertBefore($(username+'_blItem'), null);
}

function addGroupToList(groupname) {
   var bList = $('buddylist');
   
   bList.innerHTML = (groupname=='Offline' ? bList.innerHTML : '') + '<li id="' + groupname.replace(/\s/, '_') + '_groupTop" class="groupTop" onmousedown="return false;" onselectstart="return false;" onclick=" toggleGroup(\'' + groupname + '\');"><img id="' + groupname.replace(/\s/, '_') + '_groupArrow" src="'+contextPathJs+'/im/images/' + windowCSS + '/arrow.png" />&nbsp;&nbsp;' + groupname + 
                     (groupname!='Offline' ? ' <a href="#" class="delLink" onclick="remove_group_dialog(\'' + groupname + '\');return false;"><img src="'+contextPathJs+'/im/images/' + windowCSS + '/smallx.png" style="border:0;" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" /></a>' : '') + '</li>' + "\n" + '<ul id="' + groupname.replace(/\s/, '_') + '_group" class="group"></ul>' + (groupname!='Offline' ? bList.innerHTML : '');
}

function toggleGroup(groupname) {
   var groupList = $(groupname.replace(/\s/, '_') + '_group');
   var groupArrow = $(groupname.replace(/\s/, '_') + '_groupArrow');
   
   if(groupList.style.display != 'none') {
      groupList.style.display = 'none';
      groupArrow.src = contextPathJs+'/im/images/' + windowCSS + '/arrow_up.png';
   } else {
      groupList.style.display = 'block';
      groupArrow.src = contextPathJs+'/im/images/' + windowCSS + '/arrow.png';
   }
}

function selectBuddy(sel, username, selected) {
   if(selected === false) {
      if(curSelected != username) {
         sel.style.background = '#fff';
         sel.style.color = '#333';
      } else {
         sel.style.background = '#d0dae6';
         sel.style.color = '#000';
      }
   } else {
      sel.style.background = '#e1ebf7';
      sel.style.color = '#000';
   }
}

function clickBuddy(username) {
   if(curSelected.length > 0) {
      var sel = $(curSelected + '_blItem');   
      sel.style.background = '#fff';
      sel.style.color = '#333';
   }
   
   curSelected = username;
   
   sel = $(curSelected + '_blItem');
   sel.style.background = '#d0dae6';
   sel.style.color = '#333';
}

//选中某个专家后开始对话
//初始化专家广告信息
//增加定制的窗口对话
function onBuddyDblClick(imTitle) {
   if(curSelected.length > 0) {
      if(!$(curSelected + '_im')) {
         createIMWindow(curSelected, imTitle);
      } else {
         if(IMWindows[curSelected].popup) {
            if(IMWindows[curSelected].popup.closed) {
               IMWindows[curSelected] = IMWindows[curSelected].old;
               IMWindows[curSelected].show();
            } else {
               IMWindows[curSelected].popup.focus();
            }
         } else if(!IMWindows[curSelected].isVisible()) {
            IMWindows[curSelected].show();
            IMWindows[curSelected].toFront();
            setTimeout("scrollToBottom('" + curSelected + "_rcvd')", 125);
            setTimeout("$('" + curSelected + "_sendBox').focus();", 250);
         } else {
            IMWindows[curSelected].toFront();
            setTimeout("$('" + curSelected + "_sendBox').focus();", 250);
         }
      }
   }
}

function scrollToBottom(id) {
   $(id).scrollTop = $(id).scrollHeight - $(id).clientHeight;
}

function deleteBuddyFromList(username) {
   if(username.indexOf('_group') != -1) {
      deleteGroupFromList(username.substring(0, username.length - 6));
      return;
   }

   var usernam = username;

   var ingroup, loc;
   for (var group in buddyList) {
      for(var i=0; i<buddyList[group].length; i++) {
         if(buddyList[group][i] == username) {
            ingroup = group;
            loc = i;
            break;
         }
      }
   }

   var buddyToRmv = $(usernam+"_blItem");
   if(typeof(buddyToRmv) !== 'undefined') {
      buddyToRmv.parentNode.removeChild(buddyToRmv);
      if(buddyList[ingroup]) {
         buddyList[ingroup].splice(loc, 1);
         saveBuddyList();
      }
      Dialog.closeInfo();
   }
}

function deleteGroupFromList(groupname) {
   var groupNoSpaces = groupname.replace(/\s/, '_');
   var groupToRmv = $(groupNoSpaces+"_group");
   var groupTop   = $(groupNoSpaces+"_groupTop");
      
   if(typeof(groupToRmv) !== 'undefined') {
      groupToRmv.parentNode.removeChild(groupToRmv);
      groupTop.parentNode.removeChild(groupTop);
      delete buddyList[groupname];
      saveBuddyList();
      Dialog.closeInfo();
   } else {
      $('deletebuddy_error_msg').innerHTML = 'No such group on buddylist!';
      $('deletebuddy_error_msg').show();
      Dialog.win.updateHeight();
   }
}

function addNewBuddyToList(username, groupname) {
   if(!inArray(buddyList, username) && !$(username + '_blItem')) {      
      var xhConn = new XHConn();
      
      xhConn.connect(pingTo, "POST", "call=isuser&from="+user+"&pwd="+pass+"&username="+username, function(xh) {
         if(xh.responseText == 'not_exists') {
            $('newbuddy_error_msg').innerHTML = 'No such user is registered!';
         } else {
            if(!$(groupname.replace(/\s/, '_') + '_group')) {
               addGroupToList(groupname);
               buddyList[groupname] = [];
            }
            
            addBuddyToList(username, 'Offline');
            
            if(parseInt(xh.responseText) == 0 || parseInt(xh.responseText) == 50) {
               moveBuddy(username, 'Offline');
               $(username+'_blImg').src = contextPathJs+'/im/images/offline.png';
            } else if(parseInt(xh.responseText) == 2) {
               moveBuddy(username, groupname);
               $(username+'_blImg').src = contextPathJs+'/im/images/away.png';            
            } else {
               moveBuddy(username, groupname);
               $(username+'_blImg').src = contextPathJs+'/im/images/online.png';
            }
            
            buddyList[groupname][buddyList[groupname].length] = username;
      
            saveBuddyList();
            Windows.close('newBuddy');
         }
      });
   } else {
      $('newbuddy_error_msg').innerHTML = 'User is already on your buddy list!';
   }
}
      
function trim(text) {
   if(text == null) return null;
   return text.replace(/^[ \t]+|[ \t]+$/g, "");
}

function saveBuddyList() {  
   var xhConn = new XHConn();
   xhConn.connect(pingTo, "POST", "call=save&from="+user+"&pwd="+pass+"&list="+encodeURIComponent(buddyList.toJSONString()), null);
}

function resetPass() { 
}

function changePass() {
   var currentPw = $('currentpw').value;
   var newPw = $('newpw').value;
   var error = '';
   if(hex_md5(currentPw) == pass) {
      if(newPw == $('confirmpw').value) {
         var xhConn = new XHConn();
         
         xhConn.connect(pingTo, "POST", "call=pwdchange&from="+user+"&pwd="+hex_md5(currentPw)+"&newpwd="+newPw,
            function(xh) {
               if(xh.responseText == 'pw_changed') {
                  Dialog.closeInfo();
                  Dialog.alert('<span class="dialog_long_label">The password change was successful!'+"\n"+'Please re-login now.</span><div style="clear:both"></div>',
                               {windowParameters: {className:alertCSS, width:alertWidth, height:85},
                                ok:function(win) { Dialog.closeInfo(); Windows.close('changePass'); setTimeout('logout();', 250); }});
               } else if(xh.responseText == 'invalid_pw') {
                  error = 'The "Current Password" you entered is invalid.';
                  $('currentpw').value = '';
               } else if(xh.responseText == 'password_bad_length') {
                  error = 'Passwords must be 4 to 16 characters long!';
                  $('newpw').value = '';
                  $('confirmpw').value = '';
               } else {
                  error = 'There was a problem processing your password change. Please try again later.';
               }
            }
         );
      } else {
         error = 'Your passwords do not match!';
      }
   } else {
      error = 'The "Current Password" you entered is invalid.';
   }
   if(error.length > 0) {
      $('changepass_error_msg').innerHTML = error;
   }
}

function insertText(tti) {
   $(toWin + '_sendBox').value += tti;
   setTimeout("$('" + toWin + "_sendBox').focus();", 125);
   toggleEmoticonList();
   return false;
}

function setFont(fontname) {
   $(toWin + '_sendBox').style.display = 'none';
   $(toWin + '_sendBox').style.fontFamily = fontname + ', sans-serif';
   $(toWin + '_setFont').innerHTML = fontname;
   $(toWin + '_sendBox').style.display = 'block';
   setTimeout("$('" + toWin + "_sendBox').focus();", 125);
   toggleFontList('');
}

function setFontSize(size) {
   $(toWin + '_sendBox').style.display = 'none';
   $(toWin + '_sendBox').style.fontSize = size + 'px';
   $(toWin + '_setFontSize').innerHTML = size;
   $(toWin + '_sendBox').style.display = 'block';
   setTimeout("$('" + toWin + "_sendBox').focus();", 125);
   toggleFontSizeList('');
}

function setFontColor(color) {
   $(toWin + '_sendBox').style.color = color;
   $(toWin + '_setFontColorColor').style.backgroundColor = color;
   setTimeout("$('" + toWin + "_sendBox').focus();", 125);
   toggleFontColorList('');
}

function setStatus(status, away_msg) {
   if(status == 1) { // away
      isAway = 1;
      awayMessage = away_msg;
      $('curStatus').innerHTML = awayMessage.substring(0, 30) + (awayMessage.length > 30 ? '...' : '');
   } else { // back
      isAway = status; // 0 for avail, 99 for "friends only", 49 for "invisible"
      awayMessage = '';
      $('curStatus').innerHTML = away_msg;
   }
   $('statusList').style.display = 'none';
}

function customAway() {
   $('curStatus').style.display = 'none';
   $('customStatus').style.display = 'block';
   $('customStatus').focus();
}

function processCustomAway(e) {
   var asc = document.all ? event.keyCode : e.which;
   
   if(asc == 13) {
      isAway = 1;
      awayMessage = $('customStatus').value;
      $('curStatus').innerHTML = awayMessage.substring(0, 30) + (awayMessage.length > 30 ? '...' : '');
      $('curStatus').style.display = 'block';
      $('customStatus').style.display = 'none';      
   }
   return asc != 13;
}

function toggleAudio() {
   if(audioNotify == true) {
      audioNotify = false;
      $('toggleaudio').src = contextPathJs+'/im/images/'+windowCSS+'/audio_off.png';
   } else {
      audioNotify = true;
      $('toggleaudio').src = contextPathJs+'/im/images/'+windowCSS+'/audio_on.png';
   }
}

function toggleBold(name) {
   $(name + '_sendBox').style.display = 'none'; // horrah weird Opera 9 input refresh!
   if($(name + '_sendBox').style.fontWeight == '400') {
      $(name + '_bold').src = contextPathJs+'/im/images/' + windowCSS + '/bold_on.png';
      $(name + '_sendBox').style.fontWeight = '700';
   } else {
      $(name + '_sendBox').style.fontWeight = '400';
      $(name + '_bold').src = contextPathJs+'/im/images/' + windowCSS + '/bold_off.png';
   }
   $(name + '_sendBox').style.display = 'block'; // horrah weird Opera 9 input refresh!
   setTimeout("$('" + name + "_sendBox').focus();", 125);
}
   
function toggleItalic(name) {
   $(name + '_sendBox').style.display = 'none'; // horrah weird Opera 9 input refresh!
   if($(name + '_sendBox').style.fontStyle == 'normal') {
      $(name + '_sendBox').style.fontStyle = 'italic';
      $(name + '_italic').src = contextPathJs+'/im/images/' + windowCSS + '/italic_on.png';
   } else {
      $(name + '_sendBox').style.fontStyle = 'normal';
      $(name + '_italic').src = contextPathJs+'/im/images/' + windowCSS + '/italic_off.png';
   }
   $(name + '_sendBox').style.display = 'block'; // horrah weird Opera 9 input refresh!
   setTimeout("$('" + name + "_sendBox').focus();", 125);
} 

function toggleUnderline(name) {
   $(name + '_sendBox').style.display = 'none'; // horrah weird Opera 9 input refresh!
   if($(name + '_sendBox').style.textDecoration == 'none') {
      $(name + '_sendBox').style.textDecoration = 'underline';
      $(name + '_underline').src = contextPathJs+'/im/images/' + windowCSS + '/underline_on.png';
   } else {
      $(name + '_sendBox').style.textDecoration = 'none';
      $(name + '_underline').src = contextPathJs+'/im/images/' + windowCSS + '/underline_off.png';
   }
   $(name + '_sendBox').style.display = 'block'; // horrah weird Opera 9 input refresh!
   setTimeout("$('" + name + "_sendBox').focus();", 125);
}

function titlebarBlink(name, message, alter) {
   if(titlebarBlinker == false) {
      document.title = defaultTitle;
      return;
   }
   
   if(IMWindows[name].popup) {
      IMWindows[name].popup.titlebarBlink(name, message, alter);
      return;
   }
   
   if(alter == 0) {
      document.title = name + '!';
      blinkerTimer = setTimeout("titlebarBlink('"+name+"', '"+message+"', 1)", 1000);
   } else if(alter == 1) {
      document.title = '"' + message.substring(0, 10) + (message.length > 10 ? '...' : '') + '"';
      blinkerTimer = setTimeout("titlebarBlink('"+name+"', '"+message+"', 2)", 1000);
   } else if(alter == 2) {
      document.title = defaultTitle;
      blinkerTimer = setTimeout("titlebarBlink('"+name+"', '"+message+"', 0)", 1000);
   }
}

function blinkerOn(onoff) {
   if(onoff == true)
      titlebarBlinker = true;
   else
      titlebarBlinker = false;
}

function buttonHover(el) {
   var newsrc = el.src;
   newsrc = newsrc.replace(/_hover/, '');
   el.src = newsrc.replace(/\.png/, '_hover.png');
}

function buttonDown(el) {
   el.src = el.src.replace(/_hover\.png/, '_down.png');
}

function buttonNormal(el) {
   el.src = el.src.replace(/\_hover.png/, '.png').replace(/\_down.png/, '.png');
}

function browserWidth() {
   if (self.innerWidth) {
      return self.innerWidth;
   } else if (document.documentElement && document.documentElement.clientWidth) {
      return document.documentElement.clientWidth;
   } else if (document.body) {
      return document.body.clientWidth;
   }
   return 630;
}

function browserHeight() {
   if (self.innerWidth) {
      return self.innerHeight;
   } else if (document.documentElement && document.documentElement.clientWidth) {
      return document.documentElement.clientHeight;
   } else if (document.body) {
      return document.body.clientHeight;
   }
   return 470;
}

function randomNumber(max) {
   return Math.round(Math.random()*max);
}

function checkEmailAddr( email ) {
   var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
   if (filter.test(email)) return true;
   else return false;
}

function getElementsByCondition(condition, container) {
   container = container||document;
   var all = container.all||container.getElementsByTagName('*');
   var arr = [];
   for(var k=0;k<all.length;k++) {
      var elm = all[k];
      if(condition(elm,k))
         arr[arr.length] = elm;
   }
   return arr;
}

function getElementsByClass(node, searchClass, tag) {
   var classElements = [];
   var els = node.getElementsByTagName(tag); // use "*" for all elements
   var elsLen = els.length;
   var pattern = new RegEx("\\b"+searchClass+"\\b");
   for (i = 0, j = 0; i < elsLen; i++) {
      if ( pattern.test(els[i].className) ) {
         classElements[j] = els[i];
         j++;
      }
   }
   return classElements;
}

function isDefined(variable) {
   return (typeof(variable) == "undefined") ? false : true;
}

function inArray(arr, value)
// Returns true if the passed value is found in the
// array.  Returns false if it is not.
{
   var i;
   for (var group in arr) {
     // Matches identical (===), not just similar (==).
      for(i=0; i<arr[group].length; i++) {
         if(arr[group][i] === value)
            return true;
      }
   }
   return false;
};

function addOption(selectbox,text,value) {
   if(!isIE && !window.opera) {
      selectbox.innerHTML += '<option value="' + value + '">' + text + '</option>';
   } else {
      var optn = document.createElement("OPTION");
      optn.text = text;
      optn.value = value;
      var res = selectbox.options.add(optn);
   }
}

function removeItems(array, item) {
   var i = 0;
   while (i < array.length) {
      if (array[i] == item) {
         array.splice(i, 1);
      } else {
         i++;
      }
   }
   return array;
}

function removeAllOptions(selectbox) {
   var i;
   for(i=selectbox.options.length-1;i>=0;i--) {
      selectbox.remove(i);
   }
}

function removeOptions(selectbox, val) {
   var i;
   for(i=selectbox.options.length-1;i>=0;i--) {
      if(selectbox.options[i].value === val)
         selectbox.remove(i);
   }
}

String.prototype.isAlphaNumeric = function() {return /^[a-z0-9_\d]+$/.test (this)};

function Debug() {
   this.create = function() {
      createIMWindow('Debug', 'Debug');
   }
   
   this.write = function(text) {
      $('Debug_rcvd').innerHTML += text + "<br>\n";
   }
}

//meconsea 
function displayAdvPane(apName){
	if($(apName+'_advPaneContent').style.display == ''){
		$(apName+'_advPaneContent').style.display = 'none';
	}else{
		$(apName+'_advPaneContent').style.display = '';
	}
}

function initAdvPane(apName){
	var apIH = "";
	var xhConn = new XHConn();
    xhConn.connect(pingTo, "POST", "call=adv&username="+apName,
	function(xh){
		if(xh.responseText.length > 3){
			var responseJ = xh.responseText.parseJSON();
			var expert_t = responseJ.expert;
			if(expert_t == "0"){
				apIH = "欢迎加入"+web_name;
			}else if(expert_t == "1"){
				apIH = "<span align='center'>"+responseJ.enterpriseRealName+"</span><br>";
				var _tinfo = responseJ.enterpriseIntro;
				apIH = apIH + responseJ.enterpriseIntro.replace(/verylady/g,"<br>") + "<br>";
				apIH += "<span align='center'>"+responseJ.nickname+"</span><br>";
				apIH += responseJ.userintro;
				apIH += "<br>";
				apIH += "<div id='"+apName+"_credit'>该专家水平：<select name='exp_credit_"+apName+"' onChange=creditExp('"+apName+"')><option value='0'>请选择...</option><option value='1'>青铜</option><option value='2'>白银</option><option value='3'>黄金</option><option value='4'>白金</option><option value='5'>钻石</option></select></div>";
			}
			$(apName+"_advPane").innerHTML = apIH;
		}else{
			$(apName+"_advPane").innerHTML = apIH;
		}
	});
}

function creditExp(apName){
	if(user_role != '2'){
		alert('只有登录的会员才能对专家进行评定.');
		return false;
	}
	$(apName+'_credit').style.display='none';
	var xhConn = new XHConn();
	var cl_t = $("exp_credit_"+apName).value;
	xhConn.connect(pingTo,"POST","call=credit&username="+apName+"&level="+cl_t,function (xh){
		if(xh.responseText == 'invalid'){
			alert('专家不在线，不能进行评定。');
		}
	});
}

function F2FInit() {
   var user_name = 'guest';
   user_role = '3';  
   var xhConn = new XHConn();
   xhConn.connect(pingTo, "POST", "call=init&role="+user_role,
      function(xh) {
         if(xh.responseText == 'invalid') {
         } else if (xh.responseText.indexOf('imenterpriseSuc') != -1){
		 } else {
			var response = xh.responseText.parseJSON();
            user = response.username;
            pass = hex_md5('12345');
            defaultTitle = document.title = 'o(∩_∩)o 欢迎参与'+web_name+'！o(∩_∩)o ';
            window.onresize = fixBuddyList;
            if(!$('bl')) {
               buddyListWin = new Window('bl', {className: "dialog", width: 210, height: (browserHeight() - 60), zIndex: 100, resizable: true, 
                                                title: web_name+"即时通", draggable: true, closable: false, maximizable: false, detachable: false, minWidth: 205, minHeight: 150,
                                                showEffectOptions: {duration: 0}, hideEffectOptions: {duration: 0}});
            }
			//meconsea 去掉增加、删除好友的功能
            buddyListWin.getContent().innerHTML = '<div id="blTopToolbar"><span  class="toolbarButton">'+web_name+'</span><div id="statusSettings"><input type="text" id="customStatus" onkeypress="processCustomAway(event);" style="display:none" onblur="if($(\'customStatus\').style.display != \'none\') { $(\'customStatus\').style.display = \'none\'; $(\'curStatus\').style.display = \'block\'; }" /><a href="#" id="curStatus" onclick="toggleStatusList();return false;">在线</a></div></div><div id="blContainer"><ul id="buddylist" class="sortable box"><li style="display:none"></li></ul></div><div id="blBottomToolbar">专家登录 企业登录 会员登录</div>';
			//buddyListWin.getContent().innerHTML = '<div id="blTopToolbar"><span class="toolbarButton"><img id="addbuddy" src="'+contextPathJs+'/im/images/'+windowCSS+'/addbuddy.png" class="toolbarButton" onclick="new_buddy_dialog();" alt="添加好友" title="添加好友" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" onmousedown="buttonDown(this);" onmouseup="buttonNormal(this);" /></span><span class="toolbarButton"><img id="removebuddy" src="'+contextPathJs+'/im/images/'+windowCSS+'/removebuddy.png" class="toolbarButton" onclick="remove_buddy_dialog();" alt="删除好友" title="删除好友" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" onmousedown="buttonDown(this);" onmouseup="buttonNormal(this);" /></span><span class="toolbarButton"><img id="toggleaudio" src="'+contextPathJs+'/im/images/'+windowCSS+'/audio_'+(audioNotify ? 'on' : 'off')+'.png" onclick="toggleAudio();" alt="提示音" title="Toggle Audio" /></span><div id="statusSettings"><input type="text" id="customStatus" onkeypress="processCustomAway(event);" style="display:none" onblur="if($(\'customStatus\').style.display != \'none\') { $(\'customStatus\').style.display = \'none\'; $(\'curStatus\').style.display = \'block\'; }" /><a href="#" id="curStatus" onclick="toggleStatusList();return false;">在线</a></div></div><div id="blContainer"><ul id="buddylist" class="sortable box"><li style="display:none"></li></ul></div><div id="blBottomToolbar"><a href="#" style="-moz-outline-style: none;" onclick="logout();return false;"><img src="'+contextPathJs+'/im/images/'+windowCSS+'/signoff.png" style="border:0;" alt="登出" onmouseover="buttonHover(this);" onmouseout="buttonNormal(this);" onmousedown="buttonDown(this);" onmouseup="buttonNormal(this);" /></a></div>';
			buddyListWin.getContent().oncontextmenu = function() { return false; };
            $('bl_minimize').style.left = (buddyListWin.getSize()['width'] - 21) + 'px';
            sizeBuddyList();
            buddyListWin.showCenter(false, (((browserHeight()-40) / 2) - (buddyListWin.getSize()['height'] / 2)), (buddyListLoc == 0 ? 10 : (browserWidth() - buddyListWin.getSize()['width'] - 10)));
            buddyListWin.toFront();

            if(trim(xh.responseText).length == 0) logout();
			//meconsea 

            
            //meconsea
			//alert(response.buddy);
            pingTimer = setInterval(ping, pingFrequency);
            $('modal').style.display = 'none';   
			//meconsea 解析Json
			var enBuddyList = response.buddy;         
			for(var eLn in enBuddyList){
				if(eLn != 'toJSONString'){
					var eEle = enBuddyList[eLn];
					var eEleEnterpriseId = eEle.enterpriseId;
					var eEleEnterpriseName = eEle.enterpriseName;
					var eEleEnterpriseRealName = eEle.enterpriseRealName;
					var eEleEnterpriseCreditLevel = eEle.enterpriseCreditLevel;
					var eExperts = eEle.experts;
					for( var expertIndex in eExperts){
						if(expertIndex != 'toJSONString'){
							var eEUser= eExperts[expertIndex];
							var eEUserName = eEUser.username;
							var eEUserNickName = eEUser.nickname;
							var eEUserCreditLevel = eEUser.creditlevel;
							var eEUserOnline = eEUser.isOnline;
							if(!$(eEUserName+'_blItem'))addBuddyToListAll(eEUserName,eEUserNickName,eEUserCreditLevel, eEleEnterpriseName,eEleEnterpriseRealName,eEleEnterpriseCreditLevel);
							$(eEUserName+'_blItem').style.display='block';
							//加入组
							moveBuddy(eEUserName, eEleEnterpriseName);
							if(eEUserOnline == 0 || eEUserOnline == 50){//离线
								$(eEUserName+'_blImg').src = contextPathJs+'/im/images/offline.png';
							}else if(eEUserOnline == 2){//离开
								 $(eEUserName+'_blImg').src = contextPathJs+'/im/images/away.png';  
							}else{
								$(eEUserName+'_blImg').src = contextPathJs+'/im/images/online.png'; 
							}
						}
					}
				}
			}
			
			initLogin();
         }
      });
}

function initLogin(){
	if(blBottomToolbar){
		if(user_role == '3'){// 游客身份
			$("blBottomToolbar").innerHTML = '<span style="cursor:pointer" onclick="loginRole(0)">机构登录</span>&nbsp;&nbsp;<span style="cursor:pointer" onclick="loginRole(1)">专家登录</span>&nbsp;&nbsp;<span style="cursor:pointer" onclick="loginRole(2)">会员登录</span>&nbsp;&nbsp;';
		}
	}
}
function loginRole(_roleL){
	$('modal').style.display = 'block';
	$('registerDialog').style.display = 'none';
	$('forgotPassDialog').style.display = 'none';
	$('userRole').value = _roleL;
	if(_roleL == 0){
		$('loginSF').innerHTML="机构";
	}
	if(_roleL == 1){
		$('loginSF').innerHTML="专家";
	}
	if(_roleL == 2){
		$('loginSF').innerHTML="会员";
	}
}
